package com.cloud.utils.common;

import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: mengxiangzhong
 * @date: 2023/11/8 14:06
 * @DES: 快速构建递归树
 **/
@Data
public class Tree<T> {
    /**
     * 节点ID
     */
    private String id;
    /**
     * 显示节点文本
     */
    private String text;
    /**
     * 节点的子节点
     */
    private List<Tree<T>> nodes ;

    /**
     * 父ID
     */
    private String parentId;

    private Map<String, Object> state;


    /**
     * 快速构建
     * @param nodes
     * @param <T>
     * @return
     */
    public static <T> List<Tree<T>> build(List<Tree<T>> nodes) {

        if (nodes == null) {
            return null;
        }
        List<Tree<T>> topNodes = new ArrayList<>();
        for (Tree<T> children : nodes) {

            String pid = children.getParentId();
            if (pid.equals(children.getId() ) || "0".equals(pid)) {
                topNodes.add(children);
                continue;
            }
            for (Tree<T> parent : nodes) {
                String id = parent.getId();
                if (id != null && id.equals(pid)) {
                    if(parent.getNodes() == null ) {
                        parent.setNodes(new ArrayList<Tree<T>>());
                    }
                    parent.getNodes().add(children);
                }
            }
        }
        return topNodes;
    }

}
